<?php
namespace Umpadmin\Controller;
use Think\Controller;
class IndexController extends ExtendController {
	public function index(){
		Vendor("Page");
		$p = I("p");
		$status = I("status");
		$CATS = M("PromoCats");
		if($status=="running"){
			$where = " AND `end_time`>NOW()";
		}
		if($status=="not_running"){
			$where = " AND `end_time`<NOW()";
		}
		$total_count = $CATS->where("`sid`=".$this->sid.$where)->count("`id`");
		$PAGE = new \Page($total_count,10);
		$page = $PAGE->show();
		$cats = $CATS->where("`sid`=".$this->sid.$where)->order("`id` desc")->limit($PAGE->firstRow,$PAGE->listRows)->getField("`id`,`name`, `friend_num`, `decrease_amount`, `promo_count`, `start_time`, `end_time`, `comments`");
		if(!$cats){
			$info = "您还没有创建任何活动哦！";
		}
		foreach($cats as $k=>$cat){
			$cats[$k]["stop_time_str"]=date("m月d日H时i分",strtotime($cat["end_time"]));
			$cats[$k]["start_time_str"]=date("y年m月d日H时i分",strtotime($cat["start_time"]));
			$cats[$k]["description"]="每多邀请".$cat["friend_num"]."位好友，减钱".($cat["decrease_amount"]/100)."元，持续".$cat["promo_count"]."次";
			if(strtotime($cats[$k]["end_time"])<time()){
				$cats[$k]["status"]="stopped";
			}else{
				$cats[$k]["status"]="running";
			}
		}
		$this->assign("info",$info);
		$this->assign("cats",$cats);
		$this->assign("page",$page);
		$this->assign("usernick",$this->usernick);
		$this->display();
	}
	public function cat_list(){
		Vendor("Page");
		$p = I("p");
		$cat_id = I("cat");
		$status = I("status");
		if($status=="running"){
			$where = " AND `end_time`>NOW()";
		}
		if($status=="not_running"){
			$where = " AND `end_time`<NOW()";
		}
		$CAT = M("PromoCats");
		$catinfo = current($CAT->where("`sid`=".$this->sid." AND `id`=".$cat_id)->limit(1)->getField("`id`,`name`, `friend_num`, `decrease_amount`, `promo_count`, `start_time`, `end_time`, `comments`,`friend_link`,`qrcode_url`,`short_url`"));
		$catinfo["description"].="每多邀请".$catinfo["friend_num"]."位好友，减钱".($catinfo["decrease_amount"]/100)."元，持续".$catinfo["promo_count"]."次。详细规则见每个活动。";
		$catinfo["description"].="<h4>从".$catinfo["start_time"]."到".($catinfo["end_time"])."结束<span data-cat_id='".$catinfo["id"]."' data-start_time='".$catinfo["start_time"]."'  data-end_time='".$catinfo["end_time"]."' class='set-cat-time button button-small'>修改参与时间</span></h4>";

		$PRO = M("Promosions");
		$promotions["total_count"] = $PRO->where("`sid`=".$this->sid." AND `act_cat_id`=".$cat_id.$where)->count("`id`");
		$PAGE = new \Page($promotions["total_count"],10);
		$page = $PAGE->show();
		$promotions["item_promotion_list"]["item_promotion"] = $PRO->where("`sid`=".$this->sid." AND `act_cat_id`=".$cat_id.$where)->order("`friend_num` DESC")->limit($PAGE->firstRow,$PAGE->listRows)->getField("`id`,`activity_id`, `act_cat_id`, `name`, `participate_range`, `start_time`, `end_time`, `is_user_tag`, `user_tag`, `user_tag_id`, `is_decrease_money`, `decrease_amount`, `is_discount`, `discount_rate`, `friend_num`, `vip_user`, `sum_pay`, `pay_time_start`, `pay_time_end`, `item_iids`, `once_pay`, `status`,`is_invite`");
		foreach($promotions["item_promotion_list"]["item_promotion"] as $k=>$pro){
				$promotions["item_promotion_list"]["item_promotion"][$k]["stop_time"]=strtotime($pro["end_time"]);
				$promotions["item_promotion_list"]["item_promotion"][$k]["stop_time_str"]=date("m月d日H时i分",strtotime($pro["end_time"]));
				$promotions["item_promotion_list"]["item_promotion"][$k]["start_time_str"]=date("y年m月d日H时i分",strtotime($pro["start_time"]));
				if($promotions["item_promotion_list"]["item_promotion"][$k]["stop_time"]<time()){
					$promotions["item_promotion_list"]["item_promotion"][$k]["status"]="stopped";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["status"]="running";
				}	
				$promotions["item_promotion_list"]["item_promotion"][$k]["description"]="邀请朋友达到".$pro["friend_num"]."位，可减钱".($pro["decrease_amount"]/100)."元";
				if($pro["vip_user"]){
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='vip_user_".$k."'>必须是3个月内购买".$pro["vip_user"]."次的老用户；</span><span type='button' data-def='".$pro["vip_user"]."' data-eid='".$pro["activity_id"]."' data-id='".$k."' data-tp='vip_user' class='adv_rule cur_point button button-mini'>修改</span><br />";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='vip_user_".$k."'>不是老用户也可获得该折扣</span> <span  data-tp='vip_user' data-def='0' data-eid='".$pro["activity_id"]."' data-id='".$k."' class=\"adv_rule cur_point label label-info\">添加老用户购买次数</span>";
				}
				if($pro["sum_pay"]){
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='sum_pay_".$k."'>3个月内累计购买".$pro["sum_pay"]."元的老用户；</span><span data-def='".$pro["sum_pay"]."' type='button' data-eid='".$pro["activity_id"]."' data-id='".$k."' data-tp='sum_pay' class='adv_rule cur_point button button-mini'>修改</span><br />";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='sum_pay_".$k."'>无需累计购买金额即可获得该折扣</span> <span data-def='".$pro["sum_pay"]."' data-tp='sum_pay' data-eid='".$pro["activity_id"]."' data-id='".$k."' class=\"adv_rule cur_point label label-info\">添加老用户购买累计</span>";
				}
				if($pro["pay_time_start"] || $pro["pay_time_end"]){
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='pay_time_".$k."'>".($pro["pay_time_start"]?"在".$pro["pay_time_start"]."之后":"3个月内").($pro["pay_time_start"]&&$pro["pay_time_end"]?"、":"").($pro["pay_time_end"]?"在".$pro["pay_time_end"]."之前":"")."有过购买的老用户</span><span data-start_time='".$pro["pay_time_start"]."' data-end_time='".$pro["pay_time_end"]."' data-tp='pay_time' data-eid='".$pro["activity_id"]."' data-id='".$k."' class=\"adv_rule cur_point label label-info\">修改</span>";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='pay_time_".$k."'>无需指定购买时间即可获得该折扣</span> <span data-tp='pay_time' data-eid='".$pro["activity_id"]."' data-id='".$k."' class=\"adv_rule cur_point label label-info\">增加购买时间限定</span>";
				}
				if($pro["item_iids"]){
					$itemcont = count(explode(",",$pro["item_iids"]));
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='inf_".$k."'>3个月任意订单内包含<span class='adv-item-count".$pro["activity_id"]."'>".$itemcont."</span>款指定商品</span><span class=\"cur_point label label-info check_iids chk_".$k."\" data-eid='".$pro["activity_id"]."' data-id='".$k."'>查看</span>；<br />";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["adv_rule"][]="<span class='inf_".$k."'>无需指定购买商品即可获得该折扣</span> <span class=\"cur_point label label-info check_iids chk_".$k."\" data-eid='".$pro["activity_id"]."' data-id='".$k."'>增加订单包含商品</span>";
				}
				
		}
		
		if(!$catinfo["friend_link"]){
			$catinfo["friend_link"] = "https://hongbao.ews.m.jaeapp.com/?sid=".$this->sid."&cid=".$cat_id;
		}
		if(!$catinfo["qrcode_url"]){
			Vendor("taobaosdk.top.TopClient");
			Vendor('taobaosdk.lotusphp_runtime.Logger.Logger');
			Vendor("taobaosdk.top.RequestCheckUtil");
			Vendor("taobaosdk.top.request.MaQrcodeCommonCreateRequest");
			Vendor("taobaosdk.top.request.WirelessXcodeCreateRequest");
			$c = new \TopClient;
			$c->appkey = C("UMP_KEY");//用后台的key
			$c->secretKey = C("UMP_SECRET"); 
			$req = new \MaQrcodeCommonCreateRequest;
			$req->setType("url");
			$req->setContent($catinfo["friend_link"]);
			$req->setName("折扣".$cat_id);
			$req->setStyle("EF4F2B");
			$req->setSize("300");
			$req->setNeedEps("false");
			$req->setLogo("http://img01.taobaocdn.com/imgextra/T1Od8YFT8eXXXXXXXX");
			$resp = $c->execute($req, session("access_token"));
			if($resp->suc=="true"){
				$catinfo["qrcode_url"] = $data["qrcode_url"] = (String)$resp->modules->qrcode_d_o->qrcode_url;
				$catinfo["short_url"] = $data["short_url"] = (String)$resp->modules->qrcode_d_o->short_url;
				$data["friend_link"] = "https://hongbao.ews.m.jaeapp.com/?sid=".$this->sid."&cid=".$cat_id;
				$data["eps_url"] = (String)$resp->modules->qrcode_d_o->eps_url;
				$data["channel_id"] = (String)$resp->modules->qrcode_d_o->channel_id;
				$data["channel_name"] = (String)$resp->modules->qrcode_d_o->channel_name;
				$CAT->where("`sid`=".$this->sid." AND `id`=".$cat_id)->save($data);
			}
		}
		
		$this->assign("catid",$cat_id);
		$this->assign("cat",$catinfo);
		$this->assign("info",$err);
		$this->assign("page",$page);
		$this->assign("proms",$promotions);
		$this->assign("sid",$this->sid);
		$this->assign("usernick",$this->usernick);
		$this->display("all_list");
	}
	public function all_list(){
		Vendor("Page");
		$p = I("p");
		$info = "用户进店消费后，即可获得一个二维码，发送二维码至朋友圈，只要有朋友扫码，该用户即可获得一个折扣，朋友同时获得一个折扣。扫码的朋友越多，获得的折扣越多。";
		Vendor('taobaosdk.top.request.PromotionmiscItemActivityListGetRequest');
		Vendor('taobaosdk.top.request.TmallPromotagTagFindRequest');
		$req = new \PromotionmiscItemActivityListGetRequest;
		$req->setPageNo($p?$p:1);
		$req->setPageSize("10");
		$promotions = $this->c->execute($req, session("access_token"));
		$promotions = json_decode(json_encode($promotions),true);//整理成为数组结构
		if($promotions["code"]){
			$err = "系统出错，请联系客服并提供如下信息：".$promotions["msg"];
		}
		foreach($promotions["item_promotion_list"]["item_promotion"] as $k=>$pro){
				$promotions["item_promotion_list"]["item_promotion"][$k]["stop_time"]=strtotime($pro["end_time"]);
				$promotions["item_promotion_list"]["item_promotion"][$k]["stop_time_str"]=date("m月d日H时i分",strtotime($pro["end_time"]));
				$promotions["item_promotion_list"]["item_promotion"][$k]["start_time_str"]=date("y年m月d日H时i分",strtotime($pro["start_time"]));
				if($promotions["item_promotion_list"]["item_promotion"][$k]["stop_time"]<time()){
					$promotions["item_promotion_list"]["item_promotion"][$k]["status"]="stopped";
				}else{
					$promotions["item_promotion_list"]["item_promotion"][$k]["status"]="running";
				}	
		}
		
		$PAGE = new \Page($promotions["total_count"],10);
		$page = $PAGE->show();
		
		$this->assign("info",$err);
		$this->assign("page",$page);
		$this->assign("proms",$promotions);
		$this->assign("sid",$this->sid);
		$this->assign("ac",ACTION_NAME);
		$this->assign("usernick",$this->usernick);
		$this->display();
	}
	public function logout(){
		session('[destroy]'); // 销毁session
		$this->display("Index:login");
	}
	
	public function add_activ_item(){
		$eid=I("eid");
		$iids=I("iids");
		Vendor('taobaosdk.top.request.PromotionmiscActivityRangeAddRequest');
		$req = new \PromotionmiscActivityRangeAddRequest;
		$req->setActivityId($eid);
		$req->setIds($iids);
		$resp = $this->c->execute($req, session("access_token"));
		if($resp->is_success){
			$PROM = M("Promosions");
			$pid = $PROM->where("`activity_id`=".$eid)->getField("`id`");
			Vendor('taobaosdk.top.request.ItemsSellerListGetRequest');
			$req = new \ItemsSellerListGetRequest;
			$req->setFields("num_iid,title,pic_url,price");
			$req->setNumIids($iids);
			$items_resp = $this->c->execute($req, session("access_token"));
			foreach($items_resp->items->item as $k=>$item){
					$data[$k]["sid"]=$this->sid;
					$data[$k]["activity_id"]=$eid;
					$data[$k]["promo_id"]=$pid;
					$data[$k]["num_iid"]=(string)$item->num_iid;
					$data[$k]["title"]=(string)$item->title;
					$data[$k]["pic_url"]=(string)$item->pic_url;
					$data[$k]["price"]=(string)($item->price*100);
			}
			$ITEM = M("Items");
			$ITEM->addAll($data);
		}
		$this->ajaxReturn($resp);
	}
	public function remove_activ_item(){
		$eid=I("eid");
		$iid=I("iid");
		Vendor('taobaosdk.top.request.PromotionmiscActivityRangeRemoveRequest');
		$req = new \PromotionmiscActivityRangeRemoveRequest;
		$req->setActivityId($eid);
		$req->setIds($iid);
		$resp = $this->c->execute($req, session("access_token"));
		if($resp->is_success){
			$ITEM = M("Items");
			$ITEM->where("`num_iid`=".$iid." AND `activity_id`=".$eid)->delete();
		}
		$this->ajaxReturn($resp);
	}
	public function load_activ_items(){
		$id = I("id");
		$ITEMS = M("Items");
		$items = $ITEMS->where("`promo_id`=".$id." AND `sid`=".$this->sid)->getField("`num_iid`,`pic_url`,`recommend`,`title`");
		if(count($items)<=0){
			Vendor('taobaosdk.top.request.PromotionmiscActivityRangeListGetRequest');
			$req = new \PromotionmiscActivityRangeListGetRequest;
			$req->setActivityId($id);
			$resp = $this->c->execute($req, session("access_token"));
			if($resp->promotion_range_list){
				foreach($resp->promotion_range_list->promotion_range as $range){
					$itemids[]=$range->item_id;
				}
			}	
			if(count($itemids)>0){
				Vendor('taobaosdk.top.request.ItemsSellerListGetRequest');
				$req = new \ItemsSellerListGetRequest;
				$req->setFields("num_iid,title,pic_url");
				$req->setNumIids(implode(",",$itemids));
				$items_resp = $this->c->execute($req, session("access_token"));
				if($resp->promotion_range_list){
					foreach($resp->promotion_range_list->promotion_range as $k=>$range){
						foreach($items_resp->items->item as $item){
							if((string)$item->num_iid == (string)$range->item_id){
								$resp->promotion_range_list->promotion_range[$k]->item_title=$item->title;
								$resp->promotion_range_list->promotion_range[$k]->pic_url=$item->pic_url;
							}
						}
					}
				}
			}
		}else{
			$resp = new \stdClass();
			foreach($items as $k=>$item){
				$resp->promotion_range_list->promotion_range[$k]->activity_id=$id;
				$resp->promotion_range_list->promotion_range[$k]->item_title=$item["title"];
				$resp->promotion_range_list->promotion_range[$k]->pic_url=$item["pic_url"];
			}
		}
		
		$resp->item_count=count($itemids);
		$this->ajaxReturn($resp);
	}
	public function load_items(){
		$Q = I("get.q");
		$pg = I("get.pg");
		$items = I("get.numiids");
		if($items){
			Vendor('taobaosdk.top.request.ItemsSellerListGetRequest');
			$req = new \ItemsSellerListGetRequest;
			$req->setFields("num_iid,title,price,pic_url");
			$req->setNumIids($items);
			$resp = $this->c->execute($req, session("access_token"));
			$resp->total_results=count(explode(",",$items));
		}else{
			Vendor('taobaosdk.top.request.ItemsOnsaleGetRequest');
			$req = new \ItemsOnsaleGetRequest;
			// $req = new \ItemsInventoryGetRequest;
			$req->setFields("num_iid,title,price,pic_url");
			$req->setQ($Q);
			$req->setPageNo($pg);
			$req->setPageSize(20);
			$resp = $this->c->execute($req, session("access_token"));
			// $resp = $this->c->execute($req, "61023226da00f361e9545ba3f63b1a1319e80fb22d92ba42091447935");
		}
		$resp->q = $Q;
		$resp->pg= $pg?$pg:1;
		$resp->sumpages = ceil($resp->total_results/20);
		$this->ajaxReturn($resp);
	}
}